import { message } from 'antd';
import Axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';


const host = window.location.protocol + "//" + window.location.host;
const baseIp = process.env.NODE_ENV === 'development' ? '/tent' : host;

const service: AxiosInstance = Axios.create({
    baseURL: baseIp,
    timeout: 10 * 60 * 1000,
    withCredentials: true, // 跨域请求携带 cookie
});


Axios.defaults.headers.post['Content-Type'] = 'application/json';


service.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        return config;
    },
    (error) => {
        return Promise.reject(error.response);
    }
);


service.interceptors.response.use(
    (response: AxiosResponse): any => {
        if (response.status === 200 || response.status === 201) {
            if (response.data.code == 401) {
                localStorage.removeItem('userInfo')
                window.location.replace("/#/login");
            }
            return response.data
        } else {
            throw new Error(`HTTP error: ${response.status}`);
        }
    },
    (error) => {
        message.error(error)
        return Promise.reject({ code: 500, msg: error.message });
    }
);



const request = (url: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE', submitData: any) => {
    return service({
        url,
        method,
        [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData,
    });
};

export default request;